/********************************************************************************
 * @file    log.c
 * @author  jianqiang.xue
 * @version V1.0.0
 * @date    2021-05-16
 * @brief   LOG管理
 ********************************************************************************/

#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "ls_gpio.h"
#include "ls_syscfg.h"

#if LS_LOG_OUT == 0
#include "SEGGER_RTT.h"
#include "SEGGER_RTT_Conf.h"
#elif LS_LOG_OUT == 1
#include "bsp_uart.h"
#include "app_main.h"
#include "os_api.h"
#endif

#include "log.h"

static char *g_tx_buff = NULL;

#if LS_LOG_SWITCH
static bool g_log_init = false;

void log_init(void) {
    if (!g_log_init) {
        g_tx_buff = malloc(LS_LOG_MAX_LEN);
#if LS_LOG_OUT == 0
        SEGGER_RTT_Init();
        g_init = true;
#elif LS_LOG_OUT == 1
#if LS_UART0_EN == 0
    #error "Not UART_EN"
#endif
        if (g_tx_buff != NULL)
            g_log_init = true;
#endif
    }
}

static bool g_log_lock = 0;
void log_send(const char* format, ...) {
    if (!g_log_init) return;
    va_list p;
    uint16_t len;
    if (g_log_lock) return;
    g_log_lock = true;
    va_start(p, format);
    len = vsnprintf(g_tx_buff, LS_LOG_MAX_LEN, format, p);
    va_end(p);
#if LS_LOG_OUT == 0
    SEGGER_RTT_Write(0, g_tx_buff, len);
#elif LS_LOG_OUT == 1
    main_msgqueue_t msg;
    msg.event = MAIN_EVENT_UART0_TX;
    msg.data = (uint8_t *)g_tx_buff;
    msg.len = len;
    uint8_t ret = main_enqueue(&msg);
    if (ret != 0) {
        g_tx_buff[0] = 'G';
        g_tx_buff[1] = '0'+(-ret);
        bsp_uart_send_nbyte(BSP_UART_0, (uint8_t *)g_tx_buff, len);
    }
#endif
    g_log_lock = false;
}

//void log_send(uint8_t* data, uint16_t len) {
//    if (!g_init)
//        return;
//#if LS_LOG_OUT == 0
//    SEGGER_RTT_Write(0, data, len);
//#elif LS_LOG_OUT == 1
//    uint8_t* p = malloc(len);
//    memcpy(p, data, len);
//    main_enqueue(MAIN_EVENT_UART0_TX, p, len);
//#endif
//}

// uint8_t log_buff[16] = {0};
// void log_read(void)
//{
//     if (SEGGER_RTT_HasData(0))
//     {
//         SEGGER_RTT_Read(0, log_buff, sizeof(log_buff));
//     }
//
// }
#else
void log_set_level(uint8_t level) {
}

void log_trace(uint8_t level, const char* const format, ...) {
}
#endif
